package com.example.lightenergypolymerize.controller;


import com.alibaba.cloud.ai.tongyi.chat.TongYiChatClient;
import com.alibaba.cloud.ai.tongyi.image.TongYiImagesOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.lightenergypolymerize.entity.Answer;
import com.example.lightenergypolymerize.entity.enums.AiModelEnum;
import com.example.lightenergypolymerize.entity.enums.AiTypeEnum;
import com.example.lightenergypolymerize.service.IAnswerService;
import com.example.lightenergypolymerize.util.AppVariable;
import com.example.lightenergypolymerize.util.ResponseEntity;
import com.example.lightenergypolymerize.util.SecurityUtil;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/tongyi")
public class TongYiController {
    @Resource
    private TongYiChatClient chatClient;
    @Resource
    IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) {
        if(!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }
//        TongYiImagesOptions chatOptions = new TongYiImagesOptions();
//        chatOptions.setModel("");

        String result = "";//大模型返回的结果
        boolean addResult = false;//数据是否添加到了数据库
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(), AiTypeEnum.CHAT.getValue());
        //1.获取分布式锁示例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            //2.获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                //获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口");
            }
            result = chatClient.call(new Prompt(question))
                    .getResult()
                    .getOutput()
                    .getContent();
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.TONGYI.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            answer.setType(AiTypeEnum.CHAT.getValue());
            addResult = answerService.save(answer);
        }catch (Exception e) {
        }finally {
            //3.释放分布式锁
            rLock.unlock();
        }
        if(addResult) {
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("操作失败，请重试!");
    }

    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
        queryWrapper.eq("type", AiTypeEnum.CHAT.getValue());
        queryWrapper.eq("model", AiModelEnum.TONGYI.getValue());
        queryWrapper.orderByDesc("aid");
        List<Answer> list = answerService.list(queryWrapper);
        return ResponseEntity.succ(list);
    }
}
